import axios, { AxiosRequestConfig,AxiosResponse } from 'axios';
import qs from 'querystringify' //原qs被弃用
import { ElLoading,ElMessage } from 'element-plus';
import { getToken } from './cookies';
let loading: any;
let requestCount: number = 0;
interface Options {
    lock: boolean,
    text: string,
    background: string,
}
const options: Options = {
    lock: true,
    text: "Loading...",
    background: 'rgba(0,0,0,0.7)'
}

axios.defaults.baseURL = "http://106.52.29.161:8083/";
axios.defaults.headers.post['Content-Type'] = 'application/json';

const startLoading = () => {
    if (requestCount === 0 && !loading) loading = ElLoading.service(options);
    requestCount++;
}
const endLoading = () => {
    requestCount--;
    if(requestCount === 0) loading.close();
}

export function request(config: AxiosRequestConfig) {
    const instance = axios.create({
        //baseURL: config.baseURL || import.meta.env.MODE === 'development' ? '/api' : '', //第二个姑且先不设置
        baseURL: 'http://106.52.29.161:8083/api',
        timeout: 7000,
    })
    instance.interceptors.request.use((config) => {
        startLoading();
        if(config.method === 'get' || config.method === 'post'){
            console.log("!!!");
            if(config.params?.token || config.headers?.Authorization){  //是微北洋登录的接口
                config.params = {
                    ...config.params,
                }
            } else if (config.url === "file/upload") {  //是上传文件的接口，不需要token
                config.params = {
                    ...config.params,
                }
            } else {
                config.params = {
                    ...config.params,
                    token: getToken(),
                }  
            }
        }
        if(config.method === 'post' && config.headers && (config.headers['Content-Type'] == 'application/x-www-form-urlencoded')) config.data = qs.stringify(config.data);
        else if(config.method === 'post' && !config.headers) config.data = JSON.stringify(config.data);
        return config;
    })
    instance.interceptors.response.use((response: AxiosResponse<any>) => {
        endLoading();
        if(response.status === 200){
            const { data } = response;  //data赋值为对象
            if(data.error_code === 0 || data.success == true || !data.error_code) {
                return data;
            }
            else{
                console.log(data);
                //提示错误信息
                if(data.message[0] == 'I'){
                    return data.images;
                }else{
                    ElMessage({
                        message: data.message,
                        type: 'error',
                        duration: 2000,
                        grouping: true
                    });
                }
                console.log(data.message); //微北洋获取token时无效
                return; 
            }
        }else if(response.status === 500){
            //提示错误信息
            ElMessage.error('系统错误,请联系管理员')
            return;
        }
    },err => {
        endLoading();
        //提示错误信息
        ElMessage.error('网络错误,请刷新')
        return Promise.reject(err);
    })
    return instance(config);
}